// 房间 - Hotel
import { get } from 'lodash';
import { DataTypes, UUIDV4 } from 'sequelize';
import { MySqlModel, getSequelize } from '../db';

class Room extends MySqlModel {

}

Room.init({
  id: {
    type: DataTypes.UUID, unique: 'id', allowNull: false, defaultValue: UUIDV4, validate: { isUUID: 4 }, primaryKey: true, comment: '主键'
  },
  hotel_id: {
    type: DataTypes.UUID, unique: 'hotel_id_code', allowNull: false, validate: { isUUID: 4 }, comment: '主体'
  },
  code: {
    type: DataTypes.STRING(50), unique: 'hotel_id_code', allowNull: false, comment: '房号'
  },
  room_type_id: {
    type: DataTypes.UUID, allowNull: false, validate: { isUUID: 4 }, comment: '房型'
  },
  room_floor_id: {
    type: DataTypes.UUID, allowNull: false, validate: { isUUID: 4 }, comment: '楼层'
  },
  max_occupancy: {
    type: DataTypes.INTEGER, allowNull: false, validate: { max: 20, min: 0 }, comment: '最大可入住人数'
  },
  selectable: {
    type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false, comment: '是否可自助选房'
  },
  sequence: {
    type: DataTypes.INTEGER, allowNull: true, defaultValue: null, validate: { min: 0, max: 999999 }, comment: '排序'
  },
  created_at: {
    type: DataTypes.DATE, allowNull: false, comment: '创建时间'
  },
  updated_at: {
    type: DataTypes.DATE, allowNull: false, comment: '更新时间'
  },
  version: {
    type: DataTypes.INTEGER, allowNull: false, defaultValue: 0, comment: '版本控制'
  }
}, {
  sequelize: getSequelize(),
  tableName: 'rooms',
  comment: '房间'
});

// Room.beforeDestroy(async (instance, options) => {
//   const { transaction } = options;
//   const room = await getSequelize().models.Room
//     .findOne({
//       where: {
//         room_type_id: instance.id
//       },
//       transaction
//     });
//   if (room) {
//     throw new Error(`Used By Member ${room.room}`);
//   }
// });

Room.beforeSave(async (instance, options) => {
  const { req, transaction } = options;
  const { models } = getSequelize();
  await models.RoomRoomFeature.destroy({
    where: {
      hotel_id: instance.hotel_id,
      room_id: instance.id
    },
    transaction
  });

  // if (bulk) {
  //   const room_feature_ids = get(features, instance.code, []);
  //   // console.log(instance.code, room_feature_ids, instance.toJSON())
  //   if (Array.isArray(room_feature_ids) && room_feature_ids.length > 0) {
  //     await models.RoomRoomFeature.bulkCreate(room_feature_ids.map(e => {
  //       return {
  //         hotel_id: instance.hotel_id,
  //         room_id: instance.id,
  //         room_feature_id: e,
  //       }
  //     }), {
  //       transaction
  //     });
  //   }
  // } else {
  const room_feature_ids = get(req, 'body.room_feature_ids', []);
  if (Array.isArray(room_feature_ids) && room_feature_ids.length > 0) {
    await models.RoomRoomFeature.bulkCreate(req.body.room_feature_ids.map(e => {
      return {
        hotel_id: instance.hotel_id,
        room_id: instance.id,
        room_feature_id: e,
      }
    }), {
      transaction
    });
  }
  // }
});

Room.afterBulkCreate(async (instances, options) => {
  const { models } = getSequelize();
  const { transaction, features } = options;
  const rooms = await Room.findAll({ where: { hotel_id: instances[0].hotel_id }, transaction });
  await models.RoomRoomFeature.destroy({
    where: {
      hotel_id: instances[0].hotel_id
    },
    transaction
  });

  let rows = [];
  for (const item of rooms) {
    const room_feature_ids = get(features, item.code, []);
    if (Array.isArray(room_feature_ids) && room_feature_ids.length > 0) {
      rows = rows.concat(room_feature_ids.map(e => ({
        hotel_id: item.hotel_id,
        room_id: item.id,
        room_feature_id: e,
      }))
      );
    }
  }
  await models.RoomRoomFeature.bulkCreate(rows, {
    transaction
  });
})

Room.associate = (models) => {
  Room.belongsTo(models.RoomType, {
    foreignKey: 'room_type_id',
    targetKey: 'id',
    as: 'room_type',
    constraints: false
  })

  Room.belongsTo(models.RoomFloor, {
    foreignKey: 'room_floor_id',
    targetKey: 'id',
    as: 'room_floor',
    constraints: false
  })

  Room.belongsToMany(models.RoomFeature, { through: 'room_room_features', otherKey: 'room_feature_id', foreignKey: 'room_id', as: 'features', constraints: false });
};

export default Room;
